<?php

/*
 * 物流工具
 */

namespace app\seller\controller;

class Transport extends \app\common\controller\Seller
{

    public function index()
    {
        $model_transport = model('Common/Transport');
        $list = $model_transport->getTransportList(array('store_id' => $this->store_id), 10);
        if (!empty($list) && is_array($list)) {
            $transport = array();
            foreach ($list as $v) {
                if (!array_key_exists($v['id'], $transport)) {
                    $transport[$v['id']] = $v['title'];
                }
            }
            $extend = $model_transport->getExtendList(array('transport_id' => array('in', array_keys($transport))));
            // 整理
            if (!empty($extend)) {
                $tmp_extend = array();
                foreach ($extend as $val) {
                    $tmp_extend[$val['transport_id']]['data'][] = $val;
                    if ($val['is_default'] == 1) {
                        $tmp_extend[$val['transport_id']]['price'] = $val['sprice'];
                    }
                }
                $extend = $tmp_extend;
            }
        }

        /**
         * 页面输出
         */
        $this->assign('list', $list);
        $this->assign('extend', $extend);
        //$this->assign('show_page', $model_transport->showpage());
        $this->profile_menu('transport', 'transport');
        return $this->fetch();
    }

    /**
     * 新增运费模板
     *
     */
    public function add()
    {
        $areas = model('Common/Area')->getAreas();
        $this->assign('areas', $areas);

        $this->profile_menu('transport', 'transport');
        return $this->fetch();
    }

    public function edit()
    {
        $id = input('id/d');
        $model_transport = model('Common/Transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        $extend = $model_transport->getExtendInfo(array('transport_id' => $id));
        $this->assign('transport', $transport);
        $this->assign('extend', $extend);

        $areas = model('Common/Area')->getAreas();
        $this->assign('areas', $areas);

        $this->profile_menu('transport', 'transport');
        return $this->fetch('add');
    }

    public function delete()
    {
        //读取语言包
        $id = input('id/d');
        $model_transport = model('Common/Transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        if ($transport['store_id'] != $this->store_id) {
            return $this->error('操作失败');
        }
        //查看是否正在被使用
        if ($model_transport->isUsing($id)) {
            return $this->error('操作失败');
            $this->error('该模板正在被使用，不能删除');
        }
        if ($model_transport->delTansport(array('id' => $id))) {
            return redirect($_SERVER['HTTP_REFERER']);
        } else {
            return $this->error('操作失败');
        }
    }

    public function copy()
    {
        $id = input('id/d');
        $model_transport = model('Common/Transport');
        $transport = $model_transport->getTransportInfo(array('id' => $id));
        unset($transport['id']);
        $transport['title'] .= '的副本';
        $transport['update_time'] = time();

        try {
            \think\Db::startTrans();
            $insert = $model_transport->addTransport($transport);
            if ($insert) {
                $extend = $model_transport->getExtendList(array('transport_id' => $id));
                foreach ($extend as $k => $v) {
                    foreach ($v as $key => $value) {
                        $extend[$k]['transport_id'] = $insert;
                    }
                    unset($extend[$k]['id']);
                }
                $insert = $model_transport->addExtend($extend);
            }
            if (!$insert) {
                throw new Exception('操作失败');
            }
            \think\Db::commit();
            return redirect($_SERVER['HTTP_REFERER']);
            exit;
        } catch (Exception $e) {
            \think\Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 保存运费模板
     *
     */
    public function save()
    {
        if (!$this->request->isPost()) {
            return false;
        }

        $trans_info = array();
        $trans_info['title'] = input('post.title');
        $trans_info['send_tpl_id'] = 1;
        $trans_info['store_id'] = $this->store_id;
        $trans_info['update_time'] = TIMESTAMP;

        $model_transport = model('Common/Transport');

        $transport_id = input('post.transport_id/d');
        if ($transport_id > 0) {
            //编辑时，删除所有附加表信息
            $trans_info['id'] = $transport_id;
            $model_transport->transUpdate($trans_info);
            $model_transport->delExtend($transport_id);
        } else {
            //新增
            $transport_id = $model_transport->addTransport($trans_info);
        }
        
        if ($transport_id < 1) {
            return $this->error('操作失败');
        }
        
        //保存默认运费
        if (is_array($_POST['default']['kd'])) {
            $a = $_POST['default']['kd'];
            $trans_list[0]['area_id'] = '';
            $trans_list[0]['area_name'] = '全国';
            $trans_list[0]['snum'] = $a['start'];
            $trans_list[0]['sprice'] = $a['postage'];
            $trans_list[0]['xnum'] = $a['plus'];
            $trans_list[0]['xprice'] = $a['postageplus'];
            $trans_list[0]['is_default'] = 1;
            $trans_list[0]['transport_id'] = $transport_id;
            $trans_list[0]['transport_title'] = $trans_info['title'];
            $trans_list[0]['top_area_id'] = '';
        }
        //保存自定义地区的运费设置
        $areas = $_POST['areas']['kd'];
        $special = $_POST['special']['kd'];
        if (is_array($areas) && is_array($special)) {
            //$key需要加1，因为快递默认运费占了第一个下标
            foreach ($special as $key => $value) {
                if (empty($areas[$key]))
                    continue;
                $areas[$key] = explode('|||', $areas[$key]);
                $trans_list[$key + 1]['area_id'] = ',' . $areas[$key][0] . ',';
                $trans_list[$key + 1]['area_name'] = $areas[$key][1];
                $trans_list[$key + 1]['snum'] = $value['start'];
                $trans_list[$key + 1]['sprice'] = $value['postage'];
                $trans_list[$key + 1]['xnum'] = $value['plus'];
                $trans_list[$key + 1]['xprice'] = $value['postageplus'];
                $trans_list[$key + 1]['is_default'] = 2;
                $trans_list[$key + 1]['transport_id'] = $transport_id;
                $trans_list[$key + 1]['transport_title'] = $trans_info['title'];
                //计算省份ID
                $province = array();
                $tmp = explode(',', $areas[$key][0]);
                if (!empty($tmp) && is_array($tmp)) {
                    $city = model('Common/Area')->getCityProvince();
                    foreach ($tmp as $t) {
                        $pid = $city[$t];
                        if (!in_array($pid, $province) && !empty($pid))
                            $province[] = $pid;
                    }
                }
                if (count($province) > 0) {
                    $trans_list[$key + 1]['top_area_id'] = ',' . implode(',', $province) . ',';
                } else {
                    $trans_list[$key + 1]['top_area_id'] = '';
                }
                $i++;
            }
        }
        $result = $model_transport->addExtend($trans_list);
        if ($result) {
            return redirect('/?s=seller/transport/index&type='.input('post.type'));
        } else {
            return $this->error('操作失败');
        }
    }

    /**
     * 线下支付地区设置
     *
     */
    public function offpay_area()
    {
        $model_parea = model('Common/OffpayArea');

        $store_id = $this->store_id;
        $reg = '/(49[3-9]|5[0-2]\d|53[0-4])/';
        if ($this->request->isPost()) {
            $county = trim(input('post.country'), ',');
            if (!preg_match('/^[\d,]+$/', $county)) {
                $county = '';
            }
            
            $city = implode(',',input('post.city/a'));
            $city = preg_match_all($reg, $city, $matches);
            if($city){
                //台湾，澳门和香港是没有县的，所以要存储他们的市id
                $county .= ','.implode(',',$matches[1]);
            }
            //内置自营店ID
            $area_info = $model_parea->getAreaInfo(array('store_id' => $store_id));
            $data = array();
            $data['area_id'] = serialize(explode(',', $county));
            
            if (!$area_info) {
                $data['store_id'] = $store_id;
                $result = $model_parea->addArea($data);
            } else {
                $result = $model_parea->updateArea(array('store_id' => $store_id), $data);
            }
            
            if ($result !== false) {
                return $this->success('保存成功');
            } else {
                return $this->error('保存失败');
            }
        }

        //取出支持线下支付的县ID及上级市ID
        $parea_info = $model_parea->getAreaInfo(array('store_id' => $store_id));
        if (!empty($parea_info['area_id'])) {
            $parea_ids = @unserialize($parea_info['area_id']);
        }
        if (empty($parea_ids)) {
            $parea_ids = array();
        }

        $this->assign('areaIds', $parea_ids);

        $model_area = model('Common/Area');
        $areas = $model_area->getAreas();
        $this->assign('areas', $areas);

        //取出支持线下支付县ID的上级市ID
        $city_checked_child_array = array();

        foreach ($parea_ids as $i)
            if (isset($areas['parent'][$i]))
                $city_checked_child_array[$areas['parent'][$i]][] = $i;

        $this->assign('city_checked_child_array', $city_checked_child_array);

        //市级下面的县是不是全部支持线下支付，如果全部支持，默认选中
        //如果其中部分县支持线下支付，默认不选中但显示一个支付到付县的数量
        //格式 city_id => 下面支持到付的县ID数量
        $city_count_array = array();

        //格式 city_id => 是否选中true/false
        $city_checked_array = array();

        foreach ($city_checked_child_array as $city_id => $c) {
            $city_count_array[$city_id] = count($areas['children'][$city_id]);

            $c = count($c);
            if ($c > 0 && $c == $city_count_array[$city_id]) {
                $city_checked_array[$city_id] = true;
            }
        }
        $city = preg_match_all($reg, implode(',',$parea_ids), $matches);
        if ($city) {
            //台湾，澳门和香港是没有县的，存储的是他们的市id，要区别对待
            foreach($matches[1] as $val){
                $city_checked_array[$val] = true;
            }
        }
        $this->assign('city_count_array', $city_count_array);
        $this->assign('city_checked_array', $city_checked_array);

        //计算哪些省需要默认选中(即该省下面的所有县都支持到付，即所有市都是选中状态)
        $province_checked_array = array();
        foreach ($areas['children'][0] as $province_id) {
            $b = true;
            foreach ($areas['children'][$province_id] as $city_id) {
                if (empty($city_checked_array[$city_id])) {
                    $b = false;
                    break;
                }
            }
            if ($b)
                $province_checked_array[$province_id] = true;
        }
        $this->assign('province_checked_array', $province_checked_array);

        $area_array_json = json_encode($model_area->getAreaArrayForJson());
        $this->assign('area_array_json', $area_array_json);

        $this->profile_menu('transport', 'offpay_area');

        return $this->fetch();
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string	$menu_type	导航类型
     * @param string 	$menu_key	当前导航的menu_key
     * @return
     */
    private function profile_menu($menu_type, $menu_key = '')
    {
        $menu_array = array();
        switch ($menu_type) {
            case 'transport':
            case 'offpay_area':
                $menu_array = array(
                    1 => array('menu_key' => 'transport', 'menu_name' => '运费模板', 'menu_url' => url('seller/transport/index')),
                );
                $menu_array[] = array(
                    'menu_key' => 'offpay_area',
                    'menu_name' => '配送地区',
                    'menu_url' => url('seller/transport/offpay_area')
                );
                break;
        }
        $this->assign('member_menu', $menu_array);
        $this->assign('menu_key', $menu_key);
        $this->assign('left_nav', 'transport');
    }

}
